package net.sf.rose.jdbc.query;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import net.sf.rose.jdbc.ConstantCode;
import net.sf.rose.jdbc.bean.DbUserBean;
import net.sf.rose.jdbc.bean.FieldBean;
import net.sf.rose.jdbc.bean.ModelBean;
import net.sf.rose.jdbc.bean.TableBean;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.util.BeanWrapper;
import net.sf.rose.util.DataUtils;
import net.sf.rose.util.DateFormat;
import net.sf.rose.util.RoseRuntimeException;

/**
 * 类说明：自动拼接SQL语句
 * 
 * @author fengjian
 * @since 2013/05/18
 */
public class BeanSQL extends QuerySQL {

	public BeanSQL() {
		super();
	}

	public BeanSQL(Service service) {
		super();
		super.service = service;
	}

	/**
	 * 功能:拼装SQL查询语句
	 * 3.示例：表名：user
	 * 字段：userName 字符串；age 数字；birthday 日期；
	 * BeanDAO dao = new BeanDAO(service);
	 * BeanSQL query = dao.getQuerySQL();
	 * query.setEntityClass(UserBean.class);
	 * query.createSql();
	 * 结果sql输出：select * from user
	 */
	public void createSql() {
		StringBuilder sb = super.setSQL("SELECT * FROM ");
		sb.append(super.getTableName());
		list.clear();
	}

	/**
	 * 功能:拼装SQL查询语句
	 * 参数： pk - 主键名
	 * 3.示例：表名：user
	 * 字段：userName 字符串；age 数字；birthday 日期；
	 * BeanDAO dao = new BeanDAO(service);
	 * BeanSQL query = dao.getQuerySQL();
	 * query.setEntityClass(UserBean.class);
	 * query.createSql("784533");
	 * 结果sql输出：select * from user where userID=?
	 * 结果查询参数："784533"
	 */
	public void createSql(String pk) {
		TableBean table = super.getTableBean();
		StringBuilder sb = super.setSQL("SELECT * FROM ");
		sb.append(super.tableName);
		sb.append(" WHERE ");
		sb.append(table.getPkField().getFieldName()).append("=?");
		list.clear();
		list.add(pk);
	}

	/**
	 * 功能:拼装SQL查询语句
	 * 参数：key - 属性名
	 * 参数：val - 属性值
	 * 3.示例：表名：user
	 * 字段：userName 字符串；age 数字；birthday 日期；
	 * BeanDAO dao = new BeanDAO(service);
	 * BeanSQL query = dao.getQuerySQL();
	 * query.setEntityClass(UserBean.class);
	 * query.createSql("userName", "pingping");
	 * 结果sql输出：select * from user where userName = ?
	 */
	public void createSql(String key, Object val) {
		TableBean table = super.getTableBean();
		StringBuilder sb = super.setSQL("SELECT * FROM ");
		sb.append(super.tableName);
		sb.append(" WHERE ");
		sb.append(table.getFieldBeanByPropertyName(key).getFieldName());
		list.clear();
		if (val == null) {
			sb.append(" is null");
		} else {
			sb.append("=?");
			list.add(val);
		}
	}

	/**
	 * 功能:拼装查找数据库某表符合条件的记录集合的SQL查询语句
	 * 参数：map - 数据参数
	 * 1.根据表结构的定义meta，从map集合中找出相关的表字段值作为查询参数
	 * 2.如果字段类型是文本、数字或日期，则根据辅助判断参数拼接SQL条件语句
	 * 3.示例：表名：user
	 * 字段：userName 字符串；age 数字；birthday 日期；
	 * Map<String, Object> map = new HashMap<String, Object>();
	 * map.put("userName", "fgg");
	 * map.put("userName_link", "like");
	 * map.put("age", 20);
	 * map.put("age_link", ">");
	 * map.put("birthday_from", "2013-06-25");
	 * map.put("birthday_to", "2014-06-25");
	 * 结果sql输出：select * from USER where USER_NAME like ? and AGE>? and
	 * (BIRTHDAY>=? and BIRTHDAY<=?)
	 * 结果查询参数："%fgg%"，20，"2013-06-25"，"2014-06-25"
	 */
	public void createSql(Map<String, Object> map) {
		list.clear();
		// 获取查询条件参数
		super.getTableBean();
		StringBuilder sb = super.setSQL("SELECT * FROM ");
		sb.append(super.tableName);
		String condition = _createConditionSql(map);
		if (!condition.equals("")) {
			sb.append(" WHERE ").append(condition);
		}
	}

	/**
	 * 功能:拼装SQL查询列表语句
	 * 参数：bean - 参数对象
	 * 3.示例：表名：user
	 * 字段：userName 字符串；age 数字；birthday 日期；
	 * UserBean user = new UserBean();
	 * user.setUserName("pingping");
	 * BeanDAO dao = new BeanDAO(service);
	 * BeanSQL query = dao.getQuerySQL();
	 * query.setEntityClass(UserBean.class);
	 * query.createSql(user);
	 * 结果sql输出：select * from user where userName=?
	 * 结果查询参数："pingping"
	 */
	public void createSql(Object bean) {
		String key = null;
		Object val = null;
		list.clear();
		TableBean table = super.getTableBean();
		StringBuilder sb = super.setSQL("SELECT * FROM ");
		sb.append(super.tableName);
		BeanWrapper bw = new BeanWrapper(bean);
		FieldBean pkField = table.getPkField();
		Object pk = null;
		if (pkField != null) {
			pk = bw.get(pkField.getPropertyName());
		}
		// 如果主键存在，就根据主键作唯一性查找
		if (pk != null && !pk.toString().equals("0")) {
			sb.append(" AND ").append(pkField.getFieldName()).append("=? ");
			list.add(pk);
		}
		// 如果主键不存在，则根据非空属性查找
		else {
			for (Field f : super.getEntityClass().getDeclaredFields()) {
				// 如果属性使用transient修饰符，则不需要加入查询条件
				if (Modifier.isTransient(f.getModifiers())) {
					continue;
				}
				key = f.getName();
				val = bw.get(key);
				if (val != null && !val.equals("")) {
					FieldBean field = table.getPropertyNameFieldMap().get(key);
					if (field == null) {
						continue;
					}
					if (FieldBean.isNumberType(field)) {
						String s = val.toString();
						if (s.equals("0") || s.equals("0.0")) {
							continue;
						}
					}
					sb.append(" AND ").append(field.getFieldName()).append("=? ");
					list.add(val);
				}
			}
		}
		// 如果有条件参数
		int start = sb.indexOf(" AND ");
		if (start != -1) {
			// 将第一个条件的前置字符串“AND”换成“WHERE”
			sb.replace(start, start + 5, " WHERE ");
		}
	}

	/**
	 * 功能:拼装SQL查询语句
	 * 参数： sql - SQL语句
	 * 参数： map - 参数键值列表
	 * 3.示例：表名：user
	 * 字段：userName 字符串；age 数字；birthday 日期；
	 * String sql = "SELECT * FROM user where userName=#userName#";
	 * Map<String, Object> map = new HashMap<String, Object>();
	 * map.put("userName", "fgg");
	 * BeanDAO dao = new BeanDAO(service);
	 * BeanSQL query = dao.getQuerySQL();
	 * query.setEntityClass(UserBean.class);
	 * query.createSql(sql, map);
	 * 结果sql输出：select * from user where userName=?
	 * 结果查询参数："fgg"
	 */
	public void createSqlMap(String sql, Map<String, Object> map) {
		String key = null;
		StringBuilder sb = super.setSQL(sql);
		list.clear();
		int i = sb.indexOf("#");
		if (i == -1) {
			return;
		}
		// 替换SQL
		int j = sb.indexOf("#", i + 1);
		do {
			key = sb.substring(i + 1, j);
			list.add(map.get(key));
			sb.replace(i, j + 1, "?");
			i = sb.indexOf("#");
			j = sb.indexOf("#", i + 1);
		} while (i != -1 && j != -1);
	}

	/**
	 * 功能:拼装SQL查询列表语句
	 * 参数：sql - SQL语句
	 * 参数：bean - 参数对象
	 * 3.示例：表名：user
	 * 字段：userName 字符串；age 数字；birthday 日期；
	 * String sql = "SELECT * FROM user where userName=#userName#";
	 * UserBean user = new UserBean();
	 * user.setUserName("pingping");
	 * BeanDAO dao = new BeanDAO(service);
	 * BeanSQL query = dao.getQuerySQL();
	 * query.setEntityClass(UserBean.class);
	 * query.createSql(sql, user);
	 * 结果sql输出：select * from user where userName=?
	 * 结果查询参数："pingping"
	 */
	public void createSqlByBean(String sql, Object bean) {
		String key = null;
		this.createSql();
		StringBuilder sb = super.setSQL(sql);
		int i = sb.indexOf("#");
		if (i == -1) {
			return;
		}
		BeanWrapper bw = new BeanWrapper(bean);
		// 替换SQL
		int j = sb.indexOf("#", i + 1);
		do {
			key = sb.substring(i + 1, j);
			list.add(bw.get(key));
			sb.replace(i, j + 1, "?");
			i = sb.indexOf("#");
			j = sb.indexOf("#", i + 1);
		} while (i != -1 && j != -1);
	}

	/**
	 * 功能:拼装SQL保存语句
	 * 参数：bean - 参数对象
	 */
	public void createSaveSql(Object bean) {
		this.createSaveSql(bean, null);
	}

	/**
	 * 功能:拼装SQL保存语句
	 * 参数：bean - 参数对象
	 * 参数：forceUpdateProperties - 强制更新的属性名称，多个以逗号隔开。此参数用于需要更新Null值，或数值是0的情况。
	 */
	public void createSaveSql(Object bean, String forceUpdateProperties) {
		this.setEntityClassForce(bean.getClass());
		TableBean table = this.getTableBean();
		FieldBean field = table.getPkField();
		if (field == null) {
			throw new RoseRuntimeException(
					"表：" + table.getTableName() + "没有设置主键，无法根据主键判断要执行插入或更新操作！请使用createInsertSql或createUpdateSql方法。");
		}
		BeanWrapper bw = new BeanWrapper(bean);
		Object val = bw.get(field.getPropertyName());
		// 如果主键存在，且不是临时主键，则执行更新操作
		if (val != null && !val.equals("") && !val.toString().equals("0") && !val.toString().startsWith("TEMP")) {
			this.createUpdateSql(bean, null, forceUpdateProperties);
		}
		// 执行插入操作
		else {
			val = field.uuid(bean);
			bw.set(field.getPropertyName(), val);
			this.createInsertSql(bean);
		}
	}

	/**
	 * 功能:拼装SQL插入语句
	 * 参数：bean - 参数对象
	 */
	public void createInsertSql(Object bean) {
		this.createInsertSql(bean, null);
	}

	/**
	 * 功能:拼装SQL插入语句
	 * 
	 * @param bean                  - 参数对象
	 * @param forceUpdateProperties - 强制更新的属性名称，多个以逗号隔开。此参数用于需要更新Null值，或数值是0的情况。
	 */
	public void createInsertSql(Object bean, String forceUpdateProperties) {
		Object val = null;
		this.setEntityClassForce(bean.getClass());
		TableBean table = super.getTableBean();
		String tablename = table.getTableName();
		StringBuilder buf = new StringBuilder();
		StringBuilder valbuf = new StringBuilder();
		list.clear();
		// 给实体类添加默认数据，创建时间，更新时间，创建人，所在部门，所属机构
		Timestamp timestamp = DateFormat.getTimestamp();
		BeanWrapper bw = new BeanWrapper(bean);
		if (table.getFieldBeanByPropertyName(ModelBean.CREATE_TIME) != null) {
			bw.set(ModelBean.CREATE_TIME, timestamp);
		}
		if (table.getFieldBeanByPropertyName(ModelBean.UPDATE_TIME) != null) {
			bw.set(ModelBean.UPDATE_TIME, timestamp);
		}
		DbUserBean user = this.service.getUser();
		if (user != null) {
			if (table.getFieldBeanByPropertyName(ModelBean.CREATE_USER_ID) != null) {
				bw.set(ModelBean.CREATE_USER_ID, user.getUserID());
				bw.set(ModelBean.CREATE_USER_NAME, user.getUserName());
				bw.set(ModelBean.UPDATE_USER_ID, user.getUserID());
				bw.set(ModelBean.UPDATE_USER_NAME, user.getUserName());
			}
			if (table.getFieldBeanByPropertyName(ModelBean.DEPART_ID) != null) {
				if (bw.get(ModelBean.DEPART_ID) == null) {
					bw.set(ModelBean.DEPART_ID, user.getDepartID());
				}
			}
			if (table.getFieldBeanByPropertyName(ModelBean.ORG_ID) != null) {
				if (bw.get(ModelBean.ORG_ID) == null) {
					bw.set(ModelBean.ORG_ID, user.getOrgID());
				}
			}
		}
		Map<String, String> forceUpdateMap = new HashMap<>();
		if (forceUpdateProperties != null && forceUpdateProperties.length() > 0) {
			if (forceUpdateProperties.indexOf(',') != -1) {
				StringUtils.split(forceUpdateProperties, ',');
				for (String str : StringUtils.split(forceUpdateProperties, ',')) {
					forceUpdateMap.put(str, str);
				}
			} else {
				forceUpdateMap.put(forceUpdateProperties, forceUpdateProperties);
			}
		}
		// 拼接SQL文
		buf.append("INSERT INTO ");
		buf.append(tablename);
		buf.append("(");
		valbuf.append("VALUES(");
		for (FieldBean field : table.getFields()) {
			// 如果不需要持久化
			if (!field.isPresist()) {
				continue;
			}
			// 是否需要强制更新
			boolean force = forceUpdateMap.get(field.getPropertyName()) == null ? false : true;
			val = bw.get(field.getPropertyName());
			if (val == null || val.equals("")) {
				continue;
			}
			// 如果属性是数字列表
			if (field.getType().equals(ConstantCode.DATA_TYPE_INT_LIST)) {
				if (val != null) {
					int[] arr = (int[]) val;
					if (arr.length > 0) {
						StringBuilder sb = new StringBuilder();
						for (int i = 0; i < arr.length; i++) {
							sb.append(arr[i]).append(",");
						}
						val = sb.substring(0, sb.length() - 1);
					} else {
						continue;
					}
				}
			}
			// 如果属性是文本列表
			else if (field.getType().equals(ConstantCode.DATA_TYPE_STRING_LIST)) {
				if (val != null) {
					String[] arr = (String[]) val;
					if (arr.length > 0) {
						StringBuilder sb = new StringBuilder();
						for (int i = 0; i < arr.length; i++) {
							sb.append(arr[i]).append(",");
						}
						val = sb.substring(0, sb.length() - 1);
					} else {
						continue;
					}
				}
			}
			// 如果是字符串
			else if (val instanceof String) {
				// 如果是多空格的空字符串
				if (val.toString().trim().equals("")) {
					continue;
				}
			}
			// 如果是日期
			else if (val instanceof java.util.Date) {
				val = new java.sql.Timestamp(((java.util.Date) val).getTime());
			}
			// 如果是数字
			else if (FieldBean.isNumberType(field)) {
				if (field.isPk()) {
					// 如果没有正常值
					String s = val.toString().trim();
					if (s.equals("")) {
						continue;
					} else {
						if (force && (s.equals("0") || s.equals("0.0"))) {
							val = 0;
						}
					}
				}
			}
			// 如果是布尔型
			else if (FieldBean.isBoolean(field)) {
				boolean b = (boolean) val;
				val = b ? 1 : 0;
			}
			buf.append(field.getFieldName());
			buf.append(",");
			valbuf.append("?,");
			this.list.add(val);
		}
		buf.replace(buf.length() - 1, buf.length(), ")");
		valbuf.replace(valbuf.length() - 1, valbuf.length(), ")");
		buf.append(valbuf);
		super.sql = buf;
	}

	/**
	 * 功能:根据主键拼装SQL更新语句
	 * 
	 * @param bean - 参数对象
	 */
	public void createUpdateSql(Object bean) {
		this.createUpdateSql(bean, "");
	}

	/**
	 * 功能:根据主键拼装SQL更新语句
	 * 
	 * @param bean                  - 参数对象
	 * @param forceUpdateProperties - 强制更新的属性名称，多个以逗号隔开。此参数用于需要更新Null值，或数值是0的情况。
	 */
	public void createUpdateSql(Object bean, String forceUpdateProperties) {
		Map<String, Object> data = new HashMap<>();
		this.setEntityClassForce(bean.getClass());
		TableBean table = super.getTableBean();
		FieldBean field = table.getPkField();
		BeanWrapper bw = new BeanWrapper(bean);
		Object val = bw.get(field.getPropertyName());
		data.put(field.getPropertyName(), val);
		this.createUpdateSql(bean, data, forceUpdateProperties);
	}

	/**
	 * 功能:拼装SQL更新语句
	 * 参数：bean - 参数对象
	 * 参数：data - 更新条件(此值允许null，则更新条件是主键)
	 * UserBean user = new UserBean();
	 * user.setUserName("pingping");
	 * Map<String, Object> map = new HashMap<String, Object>();
	 * map.put("age", 20);
	 * map.put("age_link", ">");
	 * BeanDAO dao = new BeanDAO(service);
	 * BeanSQL query = dao.getQuerySQL();
	 * query.setEntityClass(UserBean.class);
	 * query.createUpdateSql(sql, map);
	 * 结果sql输出：UPDATE user SET username=? WHERE age>?
	 * 结果参数："pingping",20
	 */
	public void createUpdateSql(Object bean, Map<String, Object> data) {
		this.createUpdateSql(bean, data, null);
	}

	/**
	 * 功能:根据主键拼装选择更新某些属性的SQL语句
	 * 参数：propertyNames - 要更新的参数名称
	 * 参数：bean - 参数对象
	 */
	public void createUpdateSql(String propertyNames, Object bean) {
		// 重新创建一个实体类
		Object to = DataUtils.getInstance(this.getClass(), bean.getClass().getName());
		BeanWrapper bf = new BeanWrapper(bean);
		BeanWrapper bt = new BeanWrapper(to);
		this.setEntityClassForce(bean.getClass());
		TableBean table = super.getTableBean();
		// 将主键作为条件
		Map<String, Object> data = new HashMap<>();
		FieldBean field = table.getPkField();
		data.put(field.getPropertyName(), bf.get(field.getPropertyName()));
		// 将要更新的属性复制过来
		if (propertyNames.indexOf(',') == -1) {
			Object val = bf.get(propertyNames);
			if (val != null) {
				bt.set(propertyNames, val);
			}
		} else {
			for (String key : StringUtils.split(propertyNames, ',')) {
				Object val = bf.get(key);
				if (val != null) {
					bt.set(key, val);
				}
			}
		}
		this.createUpdateSql(to, data, propertyNames);
	}

	/**
	 * 功能:拼装SQL更新语句
	 * 参数：bean - 参数对象
	 * 参数：map - 更新条件(此值允许null，则更新条件是主键)
	 * 参数：forceUpdateProperties - 强制更新的属性名称，多个以逗号隔开。此参数用于需要更新Null值，或数值是0的情况。
	 * 3.示例：表名：user
	 * 字段：userName 字符串；age 数字；birthday 日期；
	 * UserBean user = new UserBean();
	 * user.setUserName("pingping");
	 * Map<String, Object> map = new HashMap<String, Object>();
	 * map.put("age", 20);
	 * map.put("age_link", ">");
	 * BeanDAO dao = new BeanDAO(service);
	 * BeanSQL query = dao.getQuerySQL();
	 * query.setEntityClass(UserBean.class);
	 * query.createUpdateSql(user, map);
	 * 结果sql输出：UPDATE user SET username=? WHERE age>?
	 * 结果参数："pingping",20
	 */
	public void createUpdateSql(Object bean, Map<String, Object> map, String forceUpdateProperties) {
		this.setEntityClassForce(bean.getClass());
		TableBean table = super.getTableBean();
		BeanWrapper bw = new BeanWrapper(bean);
		// 给实体类添加默认数据，更新人和更新时间
		Timestamp timestamp = DateFormat.getTimestamp();
		if (table.getFieldBeanByPropertyName(ModelBean.UPDATE_TIME) != null) {
			bw.set(ModelBean.UPDATE_TIME, timestamp);
		}
		DbUserBean user = this.service.getUser();
		if (user != null) {
			if (table.getFieldBeanByPropertyName(ModelBean.UPDATE_USER_ID) != null) {
				bw.set(ModelBean.UPDATE_USER_ID, user.getUserID());
				bw.set(ModelBean.UPDATE_USER_NAME, user.getUserName());
			}
		}
		Map<String, String> forceUpdateMap = new HashMap<>();
		if (forceUpdateProperties != null && forceUpdateProperties.length() > 0) {
			if (forceUpdateProperties.indexOf(',') != -1) {
				StringUtils.split(forceUpdateProperties, ',');
				for (String str : StringUtils.split(forceUpdateProperties, ',')) {
					forceUpdateMap.put(str, str);
				}
			} else {
				forceUpdateMap.put(forceUpdateProperties, forceUpdateProperties);
			}
		}
		StringBuilder buf = new StringBuilder();
		buf.append("UPDATE ");
		buf.append(table.getTableName());
		buf.append(" SET ");
		list.clear();

		Object val = null;
		FieldBean pkField = null;
		for (FieldBean field : table.getFields()) {
			// 如果不需要持久化
			if (!field.isPresist()) {
				continue;
			}
			// 如果是主键
			if (field.isPk()) {
				pkField = field;
				continue;
			}
			val = bw.get(field.getPropertyName());
			// 是否需要强制更新
			boolean force = forceUpdateMap.get(field.getPropertyName()) == null ? false : true;
			// 如果属性是数字列表
			if (field.getType().equals(ConstantCode.DATA_TYPE_INT_LIST)) {
				if (val == null) {
					// 如果不强制更新
					if (!force) {
						continue;
					}
				} else {
					int[] arr = (int[]) val;
					if (arr.length == 0) {
						// 如果不强制更新
						if (!force) {
							continue;
						} else {
							val = null;
						}
					} else {
						StringBuilder sb = new StringBuilder();
						for (int i = 0; i < arr.length; i++) {
							sb.append(arr[i]).append(",");
						}
						val = sb.substring(0, sb.length() - 1);
					}
				}
			}
			// 如果属性是文本列表
			else if (field.getType().equals(ConstantCode.DATA_TYPE_STRING_LIST)) {
				if (val == null) {
					// 如果不强制更新
					if (!force) {
						continue;
					}
				} else {
					String[] arr = (String[]) val;
					if (arr.length == 0) {
						// 如果不强制更新
						if (!force) {
							continue;
						} else {
							val = null;
						}
					} else {
						StringBuilder sb = new StringBuilder();
						for (int i = 0; i < arr.length; i++) {
							sb.append(arr[i]).append(",");
						}
						val = sb.substring(0, sb.length() - 1);
					}
				}
			}
			// 如果值为null
			else if (val == null) {
				// 如果不强制更新
				if (!force) {
					continue;
				}
			}
			// 如果值不为空
			else {
				if (val instanceof String) {
					// 如果值是空字符串
					if (val.toString().trim().equals("")) {
						// 如果不强制更新
						if (!force) {
							continue;
						} else {
							val = null;
						}
					}
				} else if (FieldBean.isNumberType(field)) {
					String s = val.toString();
					// 如果是0值，且不强制更新
					if ((s.equals("0") || s.equals("0.0"))) {
						// 如果不强制更新
						if (!force) {
							continue;
						} else {
							val = 0;
						}
					}
				} else if (val instanceof java.util.Date) {
					val = new java.sql.Timestamp(((java.util.Date) val).getTime());
				}
				// 如果是布尔型
				else if (FieldBean.isBoolean(field)) {
					boolean b = (boolean) val;
					val = b ? 1 : 0;
				}
			}
			buf.append(field.getFieldName()).append("=?, ");
			list.add(val);
		}
		// 如果没有需要更新的字段，则返回空参数列表
		if (list.size() == 0) {
			return;
		}
		buf.deleteCharAt(buf.length() - 2);
		// 如果使用主键作为更新条件
		boolean useID = false;
		if (pkField != null) {
			Object id = bw.get(pkField.getPropertyName());
			if (id != null) {
				// 拼接SQL条件语句
				buf.append(" WHERE ");
				buf.append(pkField.getFieldName());
				buf.append("=? ");
				list.add(id);
				useID = true;
			}
		}
		// 如果没有使用useID作为更新条件
		if (!useID) {
			// 尝试使用其它参数作为更新条件
			if (map != null) {
				String condition = _createConditionSql(map);
				if (!condition.equals("")) {
					// 拼接SQL条件语句
					buf.append(" WHERE ");
					buf.append(condition);
				}
			}
		}
		super.sql = buf;
	}

	/**
	 * 功能:拼装SQL删除语句,根据主键删除记录
	 * 参数：entityClass - 返回对象类型
	 * 参数：id - 主键值
	 */
	public void createDeleteSql(Class<?> entityClass, Object id) {
		this.setEntityClassForce(entityClass);
		TableBean table = super.getTableBean();
		FieldBean field = table.getPkField();
		if (field == null) {
			throw new RuntimeException("表：" + table.getTableName() + "没有设置主键，无法根据主键删除记录。");
		}
		list.clear();
		String idName = field.getFieldName();
		StringBuilder sb = new StringBuilder();
		sb.append("DELETE FROM ");
		sb.append(table.getTableName());
		sb.append(" WHERE ");
		sb.append(idName);
		sb.append("=? ");
		super.sql = sb;
		list.add(id);
	}

	/**
	 * 功能:拼装SQL删除语句,根据主键删除记录
	 * 参数：bean - 要删除的对象
	 */
	public void createDeleteSql(Object bean) {
		list.clear();
		this.setEntityClassForce(bean.getClass());
		TableBean table = super.getTableBean();
		BeanWrapper bw = new BeanWrapper(bean);
		FieldBean pkFieldBean = table.getPkField();
		if (pkFieldBean == null) {
			throw new RuntimeException("表：" + table.getTableName() + "没有设置主键，无法根据主键删除记录。");
		}
		String idName = pkFieldBean.getFieldName();
		Object id = bw.get(pkFieldBean.getPropertyName());
		StringBuilder sb = new StringBuilder();
		sb.append("DELETE FROM ");
		sb.append(table.getTableName());
		sb.append(" WHERE ");
		sb.append(idName);
		sb.append("=? ");
		super.sql = sb;
		list.add(id);
	}

	/**
	 * 功能:根据单个条件拼装SQL删除语句
	 * 
	 * @param entityClass - 返回对象类型
	 * @param key         - 条件键名
	 * @param val         - 条件键值
	 */
	public void createDeleteSql(Class<?> entityClass, String key, Object val) {
		Map<String, Object> map = new HashMap<>();
		map.put(key, val);
		this.createDeleteSql(entityClass, map);
	}

	/**
	 * 功能:拼装SQL删除语句
	 * 参数：entityClass - 返回对象类型
	 * 参数：map - 条件参数
	 */
	public void createDeleteSql(Class<?> entityClass, Map<String, Object> map) {
		Object id = null, idName = null;
		super.setEntityClass(entityClass);
		TableBean table = super.getTableBean();
		FieldBean pkFieldBean = table.getPkField();
		if (pkFieldBean != null) {
			idName = pkFieldBean.getFieldName();
			id = map.get(pkFieldBean.getPropertyName());
		}
		String conSql = "";
		list.clear();
		if (id == null) {
			conSql = " WHERE " + _createConditionSql(map);
		} else {
			conSql = " WHERE " + idName + "=?";
			list.add(id);
		}
		if (conSql.equals("")) {
			throw new RoseRuntimeException("不允许删除整个表的数据，删除SQL语句没有任何条件！");
		}
		StringBuilder sb = new StringBuilder();
		sb.append("DELETE FROM ");
		sb.append(table.getTableName());
		sb.append(conSql);
		super.sql = sb;
	}

	/**
	 * 功能:拼装批处理插入SQL语句
	 * 参数：beans - 类对象列表
	 */
	public void createBatchInsertSql(List<?> beans) {
		String key = null;
		list.clear();
		if (beans.size() == 0) {
			return;
		}
		// 给实体类添加默认数据，创建时间，更新时间，创建人，所在部门，所属机构
		this.setEntityClassForce(beans.get(0).getClass());
		TableBean table = super.getTableBean();
		boolean hasCREATE_TIME = false, hasUPDATE_TIME = false;
		if (table.getFieldBeanByPropertyName(ModelBean.CREATE_TIME) != null) {
			hasCREATE_TIME = true;
		}
		if (table.getFieldBeanByPropertyName(ModelBean.UPDATE_TIME) != null) {
			hasUPDATE_TIME = true;
		}
		String userID = null, userName = null, departID = null, orgID = null;
		DbUserBean user = this.service.getUser();
		if (user != null) {
			if (table.getFieldBeanByPropertyName(ModelBean.CREATE_USER_ID) != null) {
				userID = user.getUserID();
				userName = user.getUserName();
			}
			if (table.getFieldBeanByPropertyName(ModelBean.DEPART_ID) != null) {
				departID = user.getDepartID();
			}
			if (table.getFieldBeanByPropertyName(ModelBean.ORG_ID) != null) {
				orgID = user.getOrgID();
			}
		}
		BeanWrapper bw = new BeanWrapper();
		Timestamp timestamp = DateFormat.getTimestamp();
		for (int k = 0; k < beans.size(); k++) {
			bw.setWrappedInstance(beans.get(k));
			if (hasCREATE_TIME) {
				bw.set(ModelBean.CREATE_TIME, timestamp);
			}
			if (hasUPDATE_TIME) {
				bw.set(ModelBean.UPDATE_TIME, timestamp);
			}
			if (userID != null) {
				bw.set(ModelBean.CREATE_USER_ID, userID);
				bw.set(ModelBean.CREATE_USER_NAME, userName);
				bw.set(ModelBean.UPDATE_USER_ID, userID);
				bw.set(ModelBean.UPDATE_USER_NAME, userName);
			}
			if (departID != null) {
				bw.set(ModelBean.DEPART_ID, departID);
			}
			if (orgID != null) {
				bw.set(ModelBean.ORG_ID, orgID);
			}
		}
		// 拼接SQL文
		List<FieldBean> fields = table.getFields();
		StringBuilder sb = new StringBuilder();
		StringBuilder st = new StringBuilder();
		sb.append("insert into ").append(table.getTableName()).append('(');
		st.append("values(");
		List<String> keys = new ArrayList<>();
		FieldBean pk = null;
		for (FieldBean f : fields) {
			// 如果不需要持久化
			if (!f.isPresist()) {
				continue;
			}
			if (f.isPk()) {
				pk = table.getPkField();
			} else {
				key = f.getFieldName();
				sb.append(key).append(',');
				st.append("?,");
				keys.add(f.getPropertyName());
			}
		}
		if (pk != null && pk.getPolicy() != null) {
			sb.append(pk.getFieldName()).append(")");
			st.append("?)");
			keys.add(pk.getPropertyName());
		} else {
			sb.deleteCharAt(sb.length() - 1);
			sb.append(')');
			st.deleteCharAt(st.length() - 1);
			st.append(')');
		}
		sb.append(st.toString());
		super.sql = sb;
		// 准备参数列表
		int size = keys.size();
		for (int k = 0; k < beans.size(); k++) {
			bw.setWrappedInstance(beans.get(k));
			Object[] arr = new Object[size];
			for (int i = 0; i < size; i++) {
				arr[i] = bw.get(keys.get(i));
			}
			if (pk != null && pk.getPolicy() != null) {
				// 如果主键不存在
				if (arr[size - 1] == null || arr[size - 1].toString().equals("0")) {
					arr[size - 1] = pk.getBeanKeyGenerator().uuid(beans.get(k));
					bw.set(pk.getPropertyName(), arr[size - 1]);
				}
			}
			super.list.add(arr);
		}
		super.sql = sb;
	}

	/**
	 * 功能:拼装批处理执行SQL语句
	 * 参数：sql - 批处理SQL语句
	 * 参数：beans - 类对象列表
	 */
	public void createBatchSql(String sql, List<?> beans) {
		String key = null;
		this.setEntityClassForce(beans.get(0).getClass());
		StringBuilder sb = super.setSQL(sql);
		list.clear();
		int i = sb.indexOf("#");
		if (i == -1) {
			return;
		}
		// 拼接SQL文
		List<String> keys = new ArrayList<>();
		int j = sb.indexOf("#", i + 1);
		do {
			key = sb.substring(i + 1, j);
			keys.add(key);
			sb.replace(i, j + 1, "?");
			i = sb.indexOf("#");
			j = sb.indexOf("#", i + 1);
		} while (i != -1 && j != -1);
		// 准备参数列表
		int size = keys.size();
		BeanWrapper bw = new BeanWrapper();
		for (int k = 0; k < beans.size(); k++) {
			bw.setWrappedInstance(beans.get(k));
			Object[] arr = new Object[size];
			for (i = 0; i < size; i++) {
				arr[i] = bw.get(keys.get(i));
			}
			super.list.add(arr);
		}
	}

	/**
	 * 功能:拼装批处理执行SQL语句
	 * 参数：fields - 需要更新的字段名称
	 * 参数：beans - 类对象列表
	 */
	public void createBatchUpdateSql(String fields, List<?> beans) {
		String[] keys = StringUtils.split(fields, ',');
		this.setEntityClassForce(beans.get(0).getClass());
		list.clear();
		// 拼接SQL文
		List<String> propertyNames = new ArrayList<>();
		TableBean table = super.getTableBean();
		StringBuilder sb = new StringBuilder();
		sb.append("update ").append(table.getTableName()).append(" set ");
		for (String key : keys) {
			sb.append(table.getFieldBeanByPropertyName(key).getFieldName()).append("=?,");
			propertyNames.add(key);
		}
		sb.deleteCharAt(sb.length() - 1);
		FieldBean pkField = table.getPkField();
		sb.append(" where ").append(pkField.getFieldName()).append("=?");
		propertyNames.add(pkField.getPropertyName());
		super.setSQL(sb.toString());
		// 准备参数列表
		int size = propertyNames.size();
		BeanWrapper bw = new BeanWrapper();
		for (int k = 0; k < beans.size(); k++) {
			bw.setWrappedInstance(beans.get(k));
			Object[] arr = new Object[size];
			for (int i = 0; i < size; i++) {
				arr[i] = bw.get(propertyNames.get(i));
			}
			super.list.add(arr);
		}
	}

	/**
	 * 功能:拼装批处理执行SQL语句
	 * 参数：bean - 类对象
	 * 参数：ids - 主键列表
	 */
	public void createBatchUpdateSql(Object bean, String ids) {
		this.createUpdateSql(bean);
		this.setEntityClassForce(bean.getClass());
		TableBean table = super.getTableBean();
		FieldBean field = table.getPkField();
		this.sql.append(" where " + field.getPropertyName() + "=?");
		List<Object> mlist = super.list;
		super.list = new ArrayList<>();
		String[] array = StringUtils.split(ids, ',');
		int size = mlist.size() + 1;
		for (int i = 0; i < array.length; i++) {
			Object[] arr = new Object[size];
			for (int j = 0; j < size - 1; j++) {
				arr[j] = mlist.get(j);
			}
			arr[size - 1] = array[i];
			super.list.add(arr);
		}
	}

	/**
	 * 功能:拼装批处理执行SQL语句
	 * 参数：sql - 类对象
	 * 参数：ids - 主键列表
	 */
	public void createBatchUpdateSql2(String sql, String ids) {
		this.setSQL(sql);
		super.list = new ArrayList<>();
		String[] array = StringUtils.split(ids, ',');
		for (int i = 0; i < array.length; i++) {
			Object[] arr = new Object[1];
			arr[0] = array[i];
			super.list.add(arr);
		}
	}

	/**
	 * 功能:拼装批处理执行SQL语句
	 * 参数：sql - 类对象
	 * 参数：array - 主键列表
	 */
	public void createBatchUpdateSql2(String sql, Object[] array) {
		this.setSQL(sql);
		super.list = new ArrayList<>();
		for (int i = 0; i < array.length; i++) {
			Object[] arr = new Object[1];
			arr[0] = array[i];
			super.list.add(arr);
		}
	}

	/**
	 * 返回从Map中获取字段的名称
	 * BeanSQL用的是propertyName，MapSQL用的是fieldName
	 * 参数：field
	 */
	@Override
	public String getConditionKey(FieldBean field) {
		return field.getPropertyName();
	}

	/**
	 * 功能:设置实体类型
	 * 参数：entityClass - 实体类型
	 */
	private void setEntityClassForce(Class<?> entityClass) {
		// 如果没有设置要操作的实体类，则直接设置
		if (super.entityClass == null) {
			super.setEntityClass(entityClass);
		}
	}
}
